import type { ClinicTimeCountRespVO, GetClinicScheduleRespVO } from '@/api/clinic-schedule';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import { ref } from 'vue';
import { DAY_PERIOD_TYPE } from '@/enums/date.enums';
import { currRoute } from '@/utils/router.utils';

dayjs.extend(customParseFormat);

export function useRegistrationTime() {
  const dateType = ref(DAY_PERIOD_TYPE.AM);

  const { query } = currRoute();
  const selectDate = ref(dayjs(query.appointmentDate));

  // 判断选择项是否可预约
  function isTimeSlotAvailable(item: ClinicTimeCountRespVO) {
    const now = dayjs();
    // 获取结束时间
    const endTime = dayjs(selectDate.value.format('YYYY-MM-DD') + +' ' + item.endTime, 'YYYY-MM-DD HH:mm');
    // 预约结束时间必须在当前时间之前
    return now.isBefore(endTime, 'minute');
  }

  // 获取时间段类型
  function getTimeSlotType(visitTime: GetClinicScheduleRespVO['visitTime'][0]) {
  // 设定 12点之前为上午包括12点
  // 12点之后 18点之前为下午
  // 18点之后为晚上
    const hour = dayjs(visitTime.startTime, 'HH:mm').hour();
    if (hour < 12) {
      return DAY_PERIOD_TYPE.AM;
    }
    if (hour < 18) {
      return DAY_PERIOD_TYPE.PM;
    }
    return DAY_PERIOD_TYPE.NN;
  }

  return {
    dateType,
    selectDate,
    getTimeSlotType,
    isTimeSlotAvailable
  };
}
